package com.service.business.member.service.impl;

import com.service.business.base.controller.rep.ConfigRep;
import com.service.business.base.service.ConfigService;
import com.service.business.member.service.MemberCacheService;
import com.service.business.member.service.MemberService;
import com.service.business.order.service.OrderProductHrComboService;
import com.service.business.support.MemberCacheUtils;
import com.service.dao.constants.ConfigConstants;
import com.service.dao.enums.GradeEnum;
import com.service.dao.enums.StarGradeEnum;
import com.service.dao.model.Member;
import com.service.dao.po.MemberCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年11月15日</dd>
 * </dl>
 *
 * @author
 */

@Slf4j
@Service
public class MemberCacheServiceImpl implements MemberCacheService {

    @Autowired
    private MemberCacheUtils memberCacheUtils;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ConfigService configService;
//    @Autowired
//    private MemberJAService memberJAService;

//    @Autowired
//    private AgentReleationService agentReleationService;
//    @Autowired
//    private MemberOutService memberOutService;
//    @Autowired
//    private OrderProductOtherService orderProductOtherService;
    @Autowired
    private OrderProductHrComboService orderProductHrComboService;

    /**
     * 会员注册时，初始化
     */
    @Override
    public void initMemberCache4Register(Integer memberId, String memberAccount) {
        MemberCache memberCache = builderMemberCache(memberId, memberAccount).build();
        memberCacheUtils.setMemberCache(memberCache);
    }

    private MemberCache.MemberCacheBuilder builderMemberCache(Integer memberId, String memberAccount){
        return MemberCache.builder()
                .memberId(memberId)
                .memberAccount(memberAccount)
                .validDRUserIdList(new ArrayList<>())
                .communityAward(BigDecimal.ZERO)
                .directAward(BigDecimal.ZERO).hashRateAward(BigDecimal.ZERO)
                .indirectAward(BigDecimal.ZERO)
                .nodeAward(BigDecimal.ZERO)
                .memberGrade(GradeEnum.one.getValue())
                .starGrade(StarGradeEnum.one.getValue())
                .totalConsumption(BigDecimal.ZERO).validMember(false)
                .filReleaseNum(BigDecimal.ZERO)
                .filTeamReleaseNum(BigDecimal.ZERO)
                .umbrellaGradeOneNum(0)
                .umbrellaGradeTwoNum(0)
                .umbrellaGradeThreeNum(0)
                .umbrellaGradeFourNum(0)
                .umbrellaHashRates(BigDecimal.ZERO);
    }

    @Override
    public void initMemberPerformance2Cache(Integer memberId) {
        long startTime = System.currentTimeMillis();
        log.info("initMemberPerformance2Cache->memberId:{} start", memberId);
        memberCacheUtils.setMemberCache(initMemberPerformance(memberId));
        log.info("initMemberPerformance2Cache->memberId:{} end 耗时:{}", memberId, System.currentTimeMillis() - startTime);
    }

    @Override
    public MemberCache initMemberPerformance(Integer memberId) {
        //设置会员基本信息
        Member member = memberService.getById(memberId);
        MemberCache.MemberCacheBuilder builder = builderMemberCache(memberId, member.getUserAccount());
        builder.memberId(memberId);
        builder.memberAccount(member.getUserAccount());
        builder.memberGrade(member.getVipGrade());
        builder.starGrade(member.getStarGrade());
        //获取会员所有的出局总和
//        MemberOut memberOut = memberOutService.getLastMemberOutRecord(memberId);
        //设置会员总消费额：购买算力消费
        BigDecimal totalConsumption = getMemberTotalConsumption(memberId);
        builder.totalConsumption(totalConsumption);

        //是否为有效会员
        ConfigRep configRep = configService.getConfigRepByName(ConfigConstants.VALID_MEMBER_CONSUMPTION);
        BigDecimal validMemberLimit = BigDecimal.valueOf(Long.parseLong(configRep.getConfValue()));
        builder.validMember(totalConsumption.compareTo(validMemberLimit) >= 0);
        //设置代理商
//        memberJAService.getMemberIncome(memberId, builder, null);
//        agentReleationService.getMyAgentAward(memberId,builder);

        List<Member> memberList = memberService.selectByPidAndStatus(memberId);
        List<Integer> validMemberIdList = memberList.parallelStream().filter(item -> {
            BigDecimal totalMoney = getMemberTotalConsumption(item.getId());
            return totalMoney.compareTo(validMemberLimit) > 0;
        }).map(Member::getId).collect(Collectors.toList());
        builder.validDRUserIdList(validMemberIdList);

        return builder.build();
    }

    private BigDecimal getMemberTotalConsumption(Integer memberId) {
        return orderProductHrComboService.totalEffectiveOrderAndStatusByMemberId(memberId);
    }

    @Override
    public MemberCache getMemberCache(Integer memberId) {
        MemberCache memberCache = memberCacheUtils.getMemberCache(memberId);
        if (ObjectUtils.isEmpty(memberCache)) {
            log.debug("getMemberCache->会员<{}>信息无缓存，获取原数据 - start", memberId);
            memberCache = initMemberPerformance(memberId);
            memberCacheUtils.setMemberCache(memberCache);
            log.debug("getMemberCache->会员<{}>信息无缓存，获取原数据 - end", memberId);
        }
        return memberCache;
    }

    @Override
    public void setMemberCache(MemberCache memberCache) {
        memberCacheUtils.setMemberCache(memberCache);
    }

    @Override
    public void cacheGiftOrderPayMoney(Integer memberId, Date someday, BigDecimal payMoney) {
        memberCacheUtils.setSomedayGiftOrderTotalMoney(memberId, someday, payMoney);
    }

    @Override
    public BigDecimal getMemberTotalAward(MemberCache memberCache) {
        return memberCache.getDirectAward()
                .add(memberCache.getIndirectAward())
                .add(memberCache.getCommunityAward())
                .add(memberCache.getNodeAward());
    }

}
